import React, { useEffect, useState } from 'react';
import { useFullscreen } from 'ahooks';
import { BaseTable, features, useTablePipeline } from 'ali-react-table';
import { Button, Checkbox, DatePicker, Form, Select, Space, Tooltip, message } from 'antd';
import _ from 'lodash';
import moment from 'moment';
import { connect } from 'umi';

import { FullscreenExitOutlined, FullscreenOutlined } from '#/utils/antdIcons';
import { HttpCode } from '#/utils/contacts';
import { downloadHandle } from '#/utils/utils';

import { PageLoading, TRCheckboxModal, TRDefault } from '@/components';
import { downFile, TABLE_COLUMNS, TABLE_STYLES, USER_DATA } from './helper';
import {
  exportExcel,
  getOptionalDate,
  queryMarketList,
  settlementDatas,
  downLoadFile,
} from './servics';
import styles from './index.less';
import TRButton from '#/components/TRButton';
import { getTreeByCodes } from '@/utils';
import { TjStation } from '@/pages/ETrade/components';
import { SERVER_URL_OBJ } from '../../../../config/urlConfig';

// 表单自定义控件-交易单元

const MyStations = (props) => {
  const { value = [], onChange, options = [], treeData = [], optionAll = [], className } = props;
  const title = '交易单元';
  const isEmpty = !treeData.length;
  useEffect(() => {
    if (!value.length) {
      onChange(optionAll);
    }
  }, [optionAll]);
  const onHandleModal = async () => {
    if (isEmpty) return;
    const result = await TRCheckboxModal.show({
      title,
      value,
      treeData,
    });
    if (result?.index === 1 && result.checkedKeys.length) {
      onChange(result.checkedKeys);
    }
    TRCheckboxModal.dismiss();
  };
  const onDeselect = () => {
    if (value.length === 1) {
      onChange(optionAll);
    }
  };
  return (
    <div className={className}>
      <Select
        // value={value}
        value={
          !value.length
            ? '请选择交易单元'
            : value.length === optionAll.length
            ? '全部'
            : `${value.length}项/${optionAll.length}项`
        }
        style={{
          width: 200,
        }}
        options={options}
        maxTagCount={1}
        open={false}
        showSearch={false}
        showArrow={true}
        onClick={onHandleModal}
        onChange={onChange}
        onDeselect={onDeselect}
      />
    </div>
  );
};

const { CLIENT_ENV } = process.env;

// 结算管理 待删除
function SettleManage({ menuCode, buttonPermissions, currentUser }) {
  let [isLoading, setLoading] = useState(false),
    [errorMsg, setErrorMsg] = useState(''),
    [regions, setRegions] = useState([]), // 全部省份
    [provinceId, setProvinceId] = useState(''), // 所选省份
    [stations, setStations] = useState([]), // 全部场站（平铺）
    [stationTree, setStationTree] = useState([]), // 已选省份的场站树
    [optionAll, setOptionAll] = useState([]), // 所选省份全部场站(全选)
    [listLoading, setListLoading] = useState(true),
    [dataMap, setDataMap] = useState({}),
    [active, setActive] = useState(''),
    [tableData, setTableData] = useState([]),
    [queryForm, setQueryForm] = useState([]), // 记录查询时用的表单，批量导出有参数依赖
    [preurl, setPreurl] = useState(''), // 文件预览地址
    [checkAll, setcheckAll] = useState(false),
    [exportLoading, setexportLoading] = useState(false),
    [endDate, setEndDate] = useState(moment()),
    [dateLoding, setDateLoding] = useState(false);

  const [form] = Form.useForm();
  const [isFullscreen, { enterFullscreen, exitFullscreen }] = useFullscreen(() =>
    document.getElementById('file-container'),
  );
  useEffect(() => {
    init();
  }, []);

  /** handle data */
  async function init() {
    // 获取数据权限
    setLoading(true);
    const res = await queryMarketList(menuCode).catch(() => setLoading(false));
    if (res?.statusCode === HttpCode.SUCCESS) {
      setErrorMsg('');
      const power = getTreeByCodes(['market', 'group', 'station'], res?.json).treeOptions;
      initDataPower(power);
    } else {
      setErrorMsg(res?.message);
    }
    setLoading(false);
  }

  async function _fetchFiles(postdata) {
    // 搜索
    setListLoading(true);
    setPreurl('');
    dataMap = {};
    active = '';
    tableData = [];
    const res = await settlementDatas(postdata, provinceId).catch(() => setListLoading(false));
    if (res?.statusCode === HttpCode.SUCCESS) {
      const resMap = res?.dataList || {},
        tabs = Object.keys(resMap);
      for (const tp in resMap) {
        let tabList = [];
        for (const sid in resMap[tp]) {
          const subList = resMap[tp][sid];
          const { stationName } = stations.find((x) => x.stationId === sid);
          if (subList.length) {
            tabList = tabList.concat(subList.map((x) => ({ ...x, stationName })));
          } else {
            tabList = tabList.concat([{ stationName }]);
          }
        }
        tabList.sort((a, b) => a.stationName.localeCompare(b.stationName, 'zh'));
        dataMap[tp] = tabList;
      }
      active = tabs[0] || '';
      if (active) {
        tableData = _.cloneDeep(dataMap[active]);
      }
    }
    setDataMap(dataMap);
    setActive(active);
    setTableData(tableData);
    setListLoading(false);
  }

  async function initDataPower(data = []) {
    // 处理数据权限
    if (!data) {
      setErrorMsg('暂无数据权限');
      return;
    }
    regions = [];
    stations = [];
    data.map((x) => {
      // 省份
      (x?.children || []).map((y) => {
        // 公司
        (y?.children || []).map((z) => {
          // 场站
          stations.push(z);
        });
      });
    });
    regions = data;

    const stationsIds = _.flatten(
      regions[0]?.children?.map((i) => i?.children?.map((x) => x.stationId)),
    );
    await getEndDate(regions?.[0]?.provinceId, stationsIds);
    form.setFieldsValue({
      regions: regions?.[0]?.marketId,
    });
    setRegions(regions);
    setStations(stations);
    getStationOptions(regions?.[0]?.children);
    setProvinceId(regions?.[0]?.provinceId);
    // onFinish({
    //   regions: regions?.[0]?.value,
    //   dateRange: targetDate,
    //   stationIds: stationsIds,
    // });
    form.submit();
  }

  /** methods */
  const getStationOptions = (data) => {
    const _optionAll = _.flatten(data?.map((i) => i?.children?.map((x) => x.stationId)));
    setOptionAll(_optionAll);
    setStationTree(data);
    form.setFieldsValue({
      stationIds: _optionAll,
    });
  };

  const getEndDate = async (provinceId, stationIds) => {
    if (dateLoding) return;
    setDateLoding(true);
    form.setFieldsValue({ dateRange: undefined });
    const res = await getOptionalDate({ provinceId, stationIds });
    if (res?.statusCode === HttpCode.SUCCESS) {
      let startDate;
      const endDate = res.data ? moment(res.data) : moment();
      setEndDate(moment(res.data));
      // 当前日期大于当前月的2号
      if (moment().diff(moment().startOf('month'), 'days') > 1) {
        startDate = moment().startOf('month');
      } else {
        startDate = moment().subtract(1, 'months').startOf('month');
      }
      startDate = endDate < startDate ? endDate : startDate;
      form.setFieldsValue({ dateRange: [startDate, endDate] });
    } else {
      setErrorMsg(res?.message);
    }
    setDateLoding(false);
  };

  //切换省份
  const onRegionChange = (value, opt) => {
    form.setFieldsValue({
      stationIds: [],
    });
    getStationOptions(opt.children);
    const _optionAll = _.flatten(opt.children?.map((i) => i?.children?.map((x) => x.stationId)));
    getEndDate(opt.provinceId, _optionAll);
    setProvinceId(opt.provinceId);
  };

  const onFinish = async (values) => {
    // 查询
    let startDate = moment(values.dateRange[0]).format('YYYY-MM-DD'),
      endDate = moment(values.dateRange[1]).format('YYYY-MM-DD'),
      stationIds = values.stationIds.map((x) => Number(x));
    setQueryForm({
      startDate,
      endDate,
      stationIds,
      regions: values.regions,
    });
    _fetchFiles({
      startDate,
      endDate,
      stationIds,
    });
  };

  const _handlePreview = async (file) => {
    // 预览
    if (file.attachmentName.indexOf('.xls') > -1) {
      let url = `${SERVER_URL_OBJ[CLIENT_ENV]}/annex/annex/downLoadFile/${file.attachmentPath}`;
      let _purl = `https://view.officeapps.live.com/op/view.aspx?src=${encodeURIComponent(url)}`;
      setPreurl(_purl);
    }
    if (file.attachmentName.indexOf('.pdf') > -1) {
      const data = await downLoadFile(file.attachmentPath);
      if (data && !data.statusCode && data.size > 66) {
        const bolb = new Blob([data], { type: 'application/pdf;chartset=UTF-8' });
        setPreurl(URL.createObjectURL(bolb));
      } else {
        message.error('预览文件下载失败');
      }
    }
  };

  const _handleDownload = async (file) => {
    // 下载
    const _durl = `${SERVER_URL_OBJ[CLIENT_ENV]}/annex/annex/downLoadFile/${file.attachmentPath}`;
    downFile(_durl, file.attachmentName);
  };

  const _onBatchExport = async () => {
    // 批量导出
    setexportLoading(true);
    let files = tableData.filter((x) => x._checked === true && x.stationId);
    if (!files.length) {
      // setexportLoading(false);
      // return;
      files = tableData.filter((x) => x.stationId && x.attachmentPath);
    }
    let dataList = _.groupBy(files, 'stationId');
    for (const key in dataList) {
      dataList[key] = dataList[key].map((x) => ({
        provinceId: x.provinceId,
        groupId: x.groupId,
        attachmentName: x.attachmentName,
        attachmentPath: x.attachmentPath,
        stationId: key,
      }));
    }
    const { startDate, endDate, regions } = queryForm;
    const jsonParam = {
      startDate,
      endDate,
      dataList,
      region: regions,
      attachmentType: active,
    };
    const postForm = {
      exportType: 'settlementManage',
      jsonParam: JSON.stringify(jsonParam),
    };
    let res = await exportExcel(postForm, provinceId);
    setexportLoading(false);
    const realFileName = res.response.headers.get('content-disposition').split('filename=')[1];
    downloadHandle(res.data, decodeURI(realFileName));
  };

  /** render */
  const _renderForm = () => {
    return (
      <Form
        name="query-form"
        form={form}
        onValuesChange={(changedFields, { regions, stationIds }) => {
          if (changedFields?.stationIds?.length) {
            const provinceId = stations.find((x) => regions === x.marketId)?.provinceId;
            getEndDate(provinceId, stationIds);
          }
        }}
        layout="inline"
        onFinish={onFinish}
      >
        <Form.Item name="regions">
          <Select
            style={{ width: 200 }}
            options={regions}
            placeholder="交易中心"
            showSearch={false}
            showArrow={true}
            onChange={onRegionChange}
          />
        </Form.Item>
        <Form.Item name="stationIds">
          <TjStation style={{ width: 200 }} options={stationTree} />
        </Form.Item>
        <Form.Item name="dateRange">
          <DatePicker.RangePicker
            style={{ width: 260 }}
            placeholder={['开始日期', '结束日期']}
            format={'YYYYMMDD'}
            separator="-"
            disabled={dateLoding}
            disabledDate={(current) => {
              return current && current > moment(endDate);
            }}
          />
        </Form.Item>
      </Form>
    );
  };
  const handelReset = () => {
    const stationsIds = _.flatten(
      regions?.[0]?.children?.map((i) => i?.children?.map((x) => x.stationId)),
    );
    let targetDate = [null, null];
    // 当前日期大于当前月的2号
    if (moment().diff(moment().startOf('month'), 'days') > 1) {
      targetDate = [moment().startOf('month'), moment()];
    } else {
      targetDate = [
        moment().subtract(1, 'months').startOf('month'),
        moment().subtract(1, 'months').endOf('month'),
      ];
    }
    let obj = {
      regions: regions?.[0]?.marketId,
      dateRange: targetDate,
      stationIds: stationsIds,
    };
    onFinish(obj);
    onRegionChange(regions?.[0], regions?.[0]);
    form.setFieldsValue(obj);
  };
  const handelCheckAll = (e) => {
    let result = [...tableData];
    const { checked } = e.target;
    result = result.map((item) => ({
      ...item,
      _checkedAll: checked,
      _checked: checked,
    }));
    setTableData(result);
    setcheckAll(checked);
  };
  const inspectCheck = (tableData) => {
    const result = tableData.filter((item) => item._checkedAll);
    return result.length === tableData.length;
  };
  const _renderColumns = () => {
    return TABLE_COLUMNS.map((x) => {
      const { code } = x;
      if (code === '_stationName') {
        return {
          ...x,
          title: (
            <span style={{ marginLeft: '7px' }}>
              <Checkbox checked={checkAll} onChange={handelCheckAll}>
                交易单元
              </Checkbox>
            </span>
          ),
          render: (value, record) => {
            return (
              <div className={styles.table_checkbox_group}>
                {record.stationId ? (
                  <Checkbox
                    checked={record._checkedAll || false}
                    indeterminate={record._indeterminate || false}
                    onChange={(e) => {
                      const { checked } = e.target;
                      record._checkedAll = checked;
                      record._indeterminate = false;
                      tableData.map((x) => {
                        if (x.stationId === record.stationId) {
                          x._checked = checked;
                        }
                      });
                      setTableData([...tableData]);
                      setcheckAll(inspectCheck(tableData));
                    }}
                  >
                    <div className={styles.nameText}>
                      <Tooltip title={value}>{value}</Tooltip>
                    </div>
                  </Checkbox>
                ) : (
                  <div
                    className={styles.nameText}
                    style={{ paddingLeft: '22px', fontSize: '14px' }}
                  >
                    <Tooltip title={value}>{value}</Tooltip>
                  </div>
                )}
              </div>
            );
          },
        };
      } else if (code === 'attachmentName') {
        return {
          ...x,
          width: 280,
          title: <span style={{ marginLeft: '42px' }}>名称</span>,
          render: (value, record) => {
            return (
              <div className={styles.table_checkbox}>
                {record.stationId ? (
                  <Checkbox
                    checked={record._checked || false}
                    onChange={(e) => {
                      const { checked } = e.target;
                      record._checked = checked;
                      const goruopList = tableData.filter((x) => x.stationId === record.stationId),
                        checkedLen = goruopList.filter((x) => x._checked === true).length,
                        _indeterminate = !!checkedLen && checkedLen < goruopList.length,
                        _checkedAll = !!checkedLen && checkedLen === goruopList.length,
                        firstIdx = tableData.findIndex((x) => x.stationId === record.stationId);
                      tableData[firstIdx]._indeterminate = _indeterminate;
                      tableData[firstIdx]._checkedAll = _checkedAll;
                      setTableData([...tableData]);
                      setcheckAll(inspectCheck(tableData));
                    }}
                  >
                    {value}
                  </Checkbox>
                ) : (
                  <span>-</span>
                )}
              </div>
            );
          },
        };
      } else if (code === 'operation') {
        return {
          ...x,
          title: <span style={{ marginLeft: '32px' }}>操作</span>,
          render: (__, record) => {
            return (
              <div className={styles.table_operation}>
                {record.stationId && (
                  <>
                    <TRButton
                      onClick={() => _handleDownload(record)}
                      buttonPermissions={buttonPermissions}
                      menuCode={'settlementManageExport'}
                      type={'link'}
                    >
                      下载
                    </TRButton>
                    <span onClick={() => _handlePreview(record)}>预览</span>
                  </>
                )}
              </div>
            );
          },
        };
      }
      return { ...x };
    });
  };

  const pipeline = useTablePipeline({ components: { Checkbox } })
    .input({ dataSource: tableData, columns: _renderColumns() })
    // .primaryKey('_id')
    .use(features.autoRowSpan());
  const _renderContent = () => {
    const tabs = Object.keys(dataMap);
    if (listLoading) return <PageLoading />;
    if (!tableData.length) return <TRDefault type={'empty'} />;

    return (
      <div className={styles.boxInner}>
        <div className={styles.title}>
          <div className={styles.btns}>
            {tabs.map((tab, idx) => (
              <div
                key={idx}
                className={`${styles.btn} ${tab === active ? styles.active : ''}`}
                onClick={() => {
                  setActive(tab);
                  setcheckAll(false);
                  setTableData(_.cloneDeep(dataMap[tab]));
                }}
              >
                {tab}
              </div>
            ))}
          </div>
          <div>
            <TRButton
              onClick={_onBatchExport}
              buttonPermissions={buttonPermissions}
              menuCode={'settlementManageExport'}
              loading={exportLoading}
            >
              批量导出
            </TRButton>
          </div>
        </div>
        <div className={styles.content}>
          {/* 文件列表 */}
          <div className={styles.tableWrap}>
            <BaseTable
              {...pipeline.getProps()}
              estimatedRowHeight={36}
              useVirtual={true}
              style={TABLE_STYLES}
            />
          </div>
          {/* 文件预览区 */}
          <div className={styles.preview} id="file-container">
            <div className={styles.preview_title}>
              <span>预览</span>
              {isFullscreen ? (
                <FullscreenExitOutlined
                  className={styles.preview_icon}
                  onClick={() => exitFullscreen()}
                />
              ) : (
                <FullscreenOutlined
                  className={styles.preview_icon}
                  onClick={() => enterFullscreen()}
                />
              )}
            </div>
            <div className={styles.preview_file} id="file-container">
              <div className={styles.file_box}>
                {USER_DATA.map((item) => (
                  <div key={item}>
                    {currentUser?.name || ''}
                    {currentUser?.mobile || ''}
                  </div>
                ))}
              </div>
              {preurl && <iframe src={preurl} frameBorder={0} width={'100%'} height={'100%'} />}
            </div>
          </div>
        </div>
      </div>
    );
  };

  if (isLoading) return <PageLoading />;
  if (errorMsg)
    return (
      <div className={styles.errorBox}>
        <TRDefault type={'error'} message={errorMsg} />
      </div>
    );
  return (
    <div className={styles.container}>
      {/* 顶部工具栏 */}
      <div className={styles.toolbar}>
        <div>{_renderForm()}</div>
        <div>
          <Space size={16}>
            <Button type="primary" htmlType="submit" onClick={() => form.submit()}>
              查询
            </Button>
            <Button htmlType="button" onClick={handelReset}>
              重置
            </Button>
          </Space>
        </div>
      </div>
      <div className={styles.box}>{_renderContent()}</div>
    </div>
  );
}

export default connect(({ global }) => ({
  menuCode: global.configure.menuCode,
  currentUser: global.configure.currentUser,
  buttonPermissions: global.configure.buttonPermissions,
}))(SettleManage);
